package com.javacoo.xservice.base.support.handler.internal;

import org.springframework.stereotype.Component;

import com.javacoo.xservice.base.BaseResponse;
import com.javacoo.xservice.base.bean.SecurityBean;
import com.javacoo.xservice.base.support.security.SecurityHolder;
import com.javacoo.xservice.base.support.security.SignBean;
import com.javacoo.xservice.base.support.swaparea.SwapAreaUtils;
import com.javacoo.xservice.base.utils.FastJsonUtil;
import com.javacoo.xservice.base.utils.LogUtil;

/**
 * 返回数据签名处理器
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2017年8月18日下午3:10:29
 */
@Component
public class ResponseSignHandler extends AbstractHandler {
	@Override
	public void afterHandle(Object input) {
		if(!(input instanceof BaseResponse)){
			return;
		}
		BaseResponse rsp = (BaseResponse)input;
		try{
		    String appKey = SwapAreaUtils.getSwapAreaData().getBaseRequest().getAppKey();
            //签名
            SecurityBean securityBean = appCoreSetting.getSecurityMap().get(appKey);
            if(!securityBean.isSign()){
                return;
            }
            doSign(rsp,securityBean);
		}catch(Exception ex){
			ex.printStackTrace();
            LogUtil.error("返回参数签名失败",ex);
		}
	}
    /**
     * 索引
     * <li>自然排序</li>
     *
     * @author duanyong@jccfc.com
     * @date 2021/3/4 11:06
     * @return: int
     */
    @Override
    public int index() {
        return 3;
    }
    /**
     * 签名
     * <p>说明:</p>
     * <li></li>
     * @author DuanYong
     * @param rsp 响应对象
     * @param securityBean 安全对象
     * @since 2017年10月20日上午10:51:09
     */
    private void doSign(BaseResponse rsp,SecurityBean securityBean){
        rsp.getData().ifPresent(o -> {
            String signStr = objToString(o);
            SecurityHolder.getSignService().ifPresent(signService -> {
                String sign = signService.sign(SignBean.builder().nonce(rsp.getTransactionSn()).param(signStr).secretkey(securityBean.getSecretKey()).timestamp(rsp.getTimestamp().toString()).build());
                rsp.setSign(sign);
            });
        });
    }

    /**
     * 对象转字符串
     * <p>说明:</p>
     * <li></li>
     * @author DuanYong
     * @param data 对象
     * @return 字符串
     * @since 2017年8月22日上午9:44:38
     */
    private String objToString(Object data){
        if (data instanceof String) {
            return data.toString();
        }
        return FastJsonUtil.toJSONString(data);
    }
}
